package com.woniuxy.service.impl;

import com.woniuxy.entity.Order;
import com.woniuxy.entity.UserCart;
import com.woniuxy.entity.dto.OrderParamDTO;
import com.woniuxy.mapper.OrderMapper;
import com.woniuxy.producer.DelayProducer;
import com.woniuxy.service.OrderService;
import com.woniuxy.util.RabbitmqConst;
import com.woniuxy.util.ResponseData;
import com.woniuxy.util.SnowflakeIdGenerator;
import com.woniuxy.util.UserContext;
import lombok.AllArgsConstructor;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import com.woniuxy.entity.OrderItem;
import org.springframework.transaction.annotation.Transactional;

/**
 * @author ：CuiYC
 * @description：
 * @date ：Created in 2025/3/17 11:16
 * @modified By：
 */
@Service
@AllArgsConstructor
public class OrderServiceImpl implements OrderService {

    private OrderMapper orderMapper;

    private DelayProducer delayProducer;
    /**
     * 用户下单接口
     *      1：判断商品库存是否足够
     *      2：写入订单表和订单详情表
     *      3：修改库存
     *      4：修改购物车状态为已下单
     *      5：15分钟未付款取消订单
     * @param orderParamDTO
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public ResponseData<?> addOrder(OrderParamDTO orderParamDTO) throws ParseException, InterruptedException {
        //1：判断商品库存是否足够
        List<UserCart> userCarts = orderMapper.queryBookAndStockCount(orderParamDTO.getCartIds());
        //放库存不足的书籍名字
//        List<String> bookCountLack = new ArrayList<>();
//        for (UserCart userCart : userCarts) {
//            if (userCart.getStoreCount() < userCart.getBuyNum()) {
//                //证明书籍库存不足
//                    //谁的库存不足
//                bookCountLack.add(userCart.getName());
//            }
//        }
        List<String> bookCountLack = userCarts.stream()
                //过滤出库存不足的书籍
                .filter(
                        userCart -> userCart.getStoreCount() < userCart.getBuyNum()
                ).map(UserCart::getName).collect(Collectors.toList());
        if (!bookCountLack.isEmpty()) {
            //有库存不足的书籍
            return ResponseData.ok(bookCountLack);
        }

        //2：写入订单表和订单详情表
        Order order = new Order();
        Integer userId = UserContext.getUserId();
        order.setUserId(userId);
        order.setAddressId(orderParamDTO.getAddrId());

        BigDecimal totalPrice = BigDecimal.ZERO;
        //加 add()
        //减 subtract()
        //乘 multiply()
        //除 divide()
        for (UserCart userCart : userCarts) {
            totalPrice = totalPrice.add(userCart.getTotalPrice());
        }
        order.setTotalPrice(totalPrice);
        //订单编号不能自增
        SnowflakeIdGenerator snowflakeIdGenerator = new SnowflakeIdGenerator();
        String orderNum = String.valueOf(snowflakeIdGenerator.nextId());

        order.setOrderNum(orderNum);
        orderMapper.addOrder(order);


        //批量写入详细订单
            //不允许在循环中插入
        List<OrderItem> orderItems = new ArrayList<>();
        for (UserCart userCart : userCarts) {
            OrderItem orderItem = new OrderItem();

            orderItem.setBookId(userCart.getBookId());
            orderItem.setBuyCount(userCart.getBuyNum());
            orderItem.setPrice(userCart.getBuyPrice());
            orderItem.setSumPrice(userCart.getTotalPrice());
            orderItem.setBookName(userCart.getName());
            orderItem.setOrderId(orderNum);

            orderItems.add(orderItem);
        }
        orderMapper.batchAddOrderItem(orderItems);

        //3：批量修改库存
        orderMapper.batchUpdateBookStockCount(userCarts);

        //4：修改购物车状态为已下单
        orderMapper.updateUserCartStatus(orderParamDTO.getCartIds());

        //5：发送一个延迟15分钟的延迟队列（用户未付款取消订单）
        delayProducer.send(orderNum, "delay",15*1000);

        return ResponseData.ok();
    }
}
